package com.crrc.sandameter.common;

import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 文件工具类
 */
public class LogFileUtils {
    private static final SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    private static final SimpleDateFormat fileNameTimeFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    private static final int maxDays = 7;//保存天数上限

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String content) {
        Runnable runnable = () -> {
            //生成文件夹之后，再生成文件，不然会出错
            String strFilePath = makeFilePath();
            String time = mDateTimeFormat.format(new Date(System.currentTimeMillis()));
            // 每次写入时，都换行写
            String strContent = time + "  " + content + "\r\n";
            try {
                File file = new File(strFilePath);
                if (!file.exists()) {
                    Log.d("TestFile", "Create the file:" + strFilePath);
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                raf.seek(file.length());
                raf.write(strContent.getBytes());
                raf.close();
            } catch (Exception e) {
                Log.e("TestFile", "Error on write File:" + e);
            }
        };
        ThreadPoolInstance.INSTANCE.getSingleThreadExecutor().execute(runnable);
    }

    //生成文件路径
    private static String makeFilePath() {
        File file;
        try {
            String fileName = fileNameTimeFormat.format(new Date(System.currentTimeMillis()));
            file = new File(GlobalVariables.INSTANCE.getLogPath() + "/logs");
            file.deleteOnExit();
            if (!file.canWrite()) {
                file.mkdirs();
            }
//            return BaseConstant.VIDEO_PATH + "/logs/" + fileName + ".txt";
            return GlobalVariables.INSTANCE.getLogPath() + "/logs/" + fileName + ".txt";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    //读取指定目录下的所有TXT文件的文件内容
    private static String getFileContent(File file) {
        StringBuilder content = new StringBuilder();
        if (!file.isDirectory()) { //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {//文件格式为""文件
                try {
                    InputStream inStream = new FileInputStream(file);
                    if (inStream != null) {
                        InputStreamReader inputReader = new InputStreamReader(inStream, StandardCharsets.UTF_8);
                        BufferedReader buffReader = new BufferedReader(inputReader);
                        String line;
                        //分行读取
                        while ((line = buffReader.readLine()) != null) {
                            content.append(line).append("\n");
                        }
                        inStream.close();//关闭输入流
                    }
                } catch (java.io.FileNotFoundException e) {
                    Log.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
                    Log.d("TestFile", e.getMessage());
                }
            }
        }
        return content.toString();
    }


    private static void deleteSingleFile(String filePath) {
        File file = new File(filePath);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }
}
